/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mylibrary;

import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author nafeez
 */
public abstract class Handler extends Thread {

    private Integer queueSizeLimit;
    Queue<Message> messageQueue;

    public Handler() {
        messageQueue = new LinkedList<Message>();
        queueSizeLimit = Integer.MAX_VALUE;
    }

    public Handler(Integer queueLimit) {
        messageQueue = new LinkedList<Message>();
        queueSizeLimit = queueLimit;
    }

    synchronized public void sendMessage(Message m) throws Exception {
        if (messageQueue.size() >= queueSizeLimit) {
            throw new Exception("Queue limit exceed");
        }
        messageQueue.add(m);
        notify();
    }

    public void removeAllMessage() {
        synchronized (messageQueue) {
            messageQueue.clear();
        }
    }

    @Override
    synchronized public void run() {
        while (true) {
            Message m = null;
            synchronized (messageQueue) {
                m = messageQueue.poll();
            }
            if (m == null) {
                try {
                    wait();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            } else {
                handleMessage(m);
            }
        }
    }

    abstract public void handleMessage(Message m);
}
